<template>
  <div class="venue-detail-container">
    <!-- 返回按钮 -->
    <div class="back-header">
      <el-button icon="el-icon-arrow-left" @click="$router.go(-1)">返回</el-button>
    </div>

    <!-- 场地基本信息 -->
    <div class="venue-basic-info">
      <el-carousel :interval="4000" type="card" height="400px" class="venue-carousel">
        <el-carousel-item v-for="(image, index) in jsonToString(venue.images).split(',')" :key="index">
          <img :src="`${baseUrl}${image}`" :alt="venue.name" class="carousel-image">
        </el-carousel-item>
      </el-carousel>

      <div class="info-content">
        <div class="info-header">
          <h1 class="venue-name">{{ venue.name }}</h1>
          <div class="venue-status" :class="{ 'available': venue.status === 1 }">
            {{ venue.status === 1 ? '可用' : '维护中' }}
          </div>
        </div>

        <div class="info-grid">
          <div class="info-item">
            <i class="el-icon-office-building"></i>
            <span>类型：{{ venue.type }}</span>
          </div>
          <div class="info-item">
            <i class="el-icon-user"></i>
            <span>容纳人数：{{ venue.capacity }}人</span>
          </div>
          <div class="info-item">
            <i class="el-icon-money"></i>
            <span>价格：¥{{ venue.price }}/天</span>
          </div>
          <div class="info-item">
            <i class="el-icon-location"></i>
            <span>地址：{{ venue.address }}</span>
          </div>
        </div>

        <el-button type="primary" size="large" @click="showReservationDialog" :disabled="venue.status !== 1">
          立即预约
        </el-button>
      </div>
    </div>

    <!-- 场地详细信息 -->
    <el-tabs v-model="activeTab" class="venue-tabs">
      <el-tab-pane label="设施介绍" name="facilities">
        <div class="facilities-list">
          <div v-for="(facility, index) in JSON.parse(venue.facilities)" :key="index" class="facility-item">
            <i :class="facility.icon"></i>
            <h3>{{ facility.name }}</h3>
            <p>{{ facility.description }}</p>
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="使用须知" name="instructions">
        <div class="instructions-content">
          <h3>预订规则</h3>
          <ul>
            <li>预订时间至少提前24小时</li>
            <li>如需取消预订，请提前48小时申请</li>
            <li>超过预订时间需支付额外费用</li>
          </ul>

          <h3>注意事项</h3>
          <ul>
            <li>请爱护场地设施，如有损坏需照价赔偿</li>
            <li>禁止在场地内吸烟</li>
            <li>活动结束后请清理场地</li>
          </ul>
        </div>
      </el-tab-pane>

      <el-tab-pane label="预订记录" name="bookings">
        <el-table :data="bookingHistory" style="width: 100%">
          <el-table-column prop="startTime" label="预订日期" width="180"></el-table-column>
          <el-table-column prop="endTime" label="结束时间" width="180"></el-table-column>
          <el-table-column prop="status" label="状态">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : scope.row.status === 0 ? 'warning' : 'info'">
                {{scope.row.status === 1 ? '已确认' : scope.row.status === 0 ? '待审核' : '被拒绝' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <!-- 预约对话框 -->
    <el-dialog
      title="场地预约"
      :visible.sync="dialogVisible"
      width="50%"
      class="reservation-dialog"
    >
      <el-form :model="reservationForm" :rules="rules" ref="reservationForm" label-width="100px">
        <el-form-item label="预约时间" prop="dateRange">
          <el-date-picker
            v-model="reservationForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="参与人数" prop="participantCount">
          <el-input-number
            v-model="reservationForm.participantCount"
            :min="1"
            :max="venue.capacity"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="用途说明" prop="purpose">
          <el-input
            type="textarea"
            v-model="reservationForm.purpose"
            :rows="3"
            placeholder="请简要说明活动用途"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitReservation">提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {getVenue} from "@/api/reunion/venue";
import {addUReservation, getReservationByUserIdAndVenueId, getReservationByVenueId} from "@/api/reunion/reservation";

export default {
  name: 'VenueDetail',
  props: {
    id: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,

      venue: {
        id: 1,
        name: '阳光会议室',
        type: '会议室',
        capacity: 30,
        address: '科技园区A栋3层',
        price: 1000,
        status: 1
      },
      venueImages: [
        'https://via.placeholder.com/800x400',
        'https://via.placeholder.com/800x400',
        'https://via.placeholder.com/800x400'
      ],
      activeTab: 'facilities',
      facilities: [
        {
          icon: 'el-icon-monitor',
          name: '投影设备',
          description: '配备高清投影仪和幕布，支持多种接口连接'
        },
        {
          icon: 'el-icon-mic',
          name: '音响系统',
          description: '专业音响设备，清晰的声音传递'
        },
        {
          icon: 'el-icon-coffee-cup',
          name: '茶水服务',
          description: '提供免费茶水、咖啡等饮品'
        },
        {
          icon: 'el-icon-connection',
          name: '高速网络',
          description: '千兆光纤网络，支持视频会议'
        }
      ],
      bookingHistory: [
        {
          date: '2024-01-15',
          time: '09:00-18:00',
          status: '已确认'
        },
        {
          date: '2024-01-20',
          time: '14:00-17:00',
          status: '待审核'
        }
      ],
      dialogVisible: false,
      reservationForm: {
        dateRange: [],
        participantCount: 1,
        purpose: ''
      },
      rules: {
        dateRange: [{required: true, message: '请选择预约时间', trigger: 'change'}],
        participantCount: [{required: true, message: '请输入参与人数', trigger: 'blur'}],
        purpose: [{required: true, message: '请输入用途说明', trigger: 'blur'}]
      },
      dataList: []
    }
  },
  computed: {
    pickerOptions() {
      return {
        disabledDate: (time) => {
          const currentDate = Date.now() - 8.64e7; // 当前日期减去一天
          const date = new Date(time).toISOString().split('T')[0];
          return time.getTime() < currentDate || this.dataList.includes(date);
        }
      }
    }

  },
  methods: {
    getReservationByVenue(){
      getReservationByUserIdAndVenueId(this.id).then(response => {
        console.log('预约记录:', response.data)
        this.bookingHistory=response.data
      })
    },
    getDataList() {
      getReservationByVenueId(this.id).then(response => {
        this.dataList = response.data;
        console.log('预约日期列表:', this.dataList);
      })
    },
    jsonToString(jsonData) {
      if (!jsonData) return '';
      try {
        // 如果输入是字符串，先解析成数组
        const arr = typeof jsonData === 'string' ? JSON.parse(jsonData) : jsonData;
        // 确保是数组
        if (Array.isArray(arr)) {
          return arr.join(',');
        }
        return '';
      } catch (e) {
        // 如果解析失败，返回空字符串
        return '';
      }
    },
    async getVenueDetail(id) {
      try {
        // TODO: 调用API获取场地详情
        const response = await getVenue(id)
        console.log(response)
        this.venue = response.data
        console.log('获取场地ID:', id)
      } catch (error) {
        this.$message.error('获取场地详情失败')
      }
    },
    showReservationDialog() {
      this.dialogVisible = true
    },
    submitReservation() {
      this.$refs.reservationForm.validate(valid => {
        if (valid) {
          // TODO: 调用预约API
          console.log(this.reservationForm)

          let data = {
            venueId: this.id,
            participantCount: this.reservationForm.participantCount,
            purpose: this.reservationForm.purpose,
            startTime: this.reservationForm.dateRange[0],
            endTime: this.reservationForm.dateRange[1]
          }
          addUReservation(data)
          this.$message.success('预约提交成功，请等待审核')
          this.dialogVisible = false
        }
      })
    }
  },
  created() {
    // 根据props的id获取场地详情
    this.getVenueDetail(this.id)
    this.getDataList()
    this.getReservationByVenue()
  }
}
</script>

<style lang="scss" scoped>
.venue-detail-container {
  padding: 24px;
  animation: fadeIn 0.5s ease-out;
}

.back-header {
  margin-bottom: 24px;
}

.venue-basic-info {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-bottom: 24px;

  .venue-carousel {
    .carousel-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .info-content {
    padding: 24px;

    .info-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24px;

      .venue-name {
        font-size: 28px;
        font-weight: 500;
        color: #2c3e50;
        margin: 0;
      }

      .venue-status {
        padding: 6px 12px;
        border-radius: 4px;
        background: #f56c6c;
        color: white;
        font-size: 14px;

        &.available {
          background: #67c23a;
        }
      }
    }

    .info-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 20px;
      margin-bottom: 24px;

      .info-item {
        display: flex;
        align-items: center;
        color: #606266;

        i {
          font-size: 20px;
          margin-right: 8px;
          color: #409EFF;
        }
      }
    }
  }
}

.venue-tabs {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 24px;

  .facilities-list {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 24px;
    padding: 20px 0;

    .facility-item {
      text-align: center;
      padding: 20px;
      border-radius: 8px;
      background: #f5f7fa;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }

      i {
        font-size: 36px;
        color: #409EFF;
        margin-bottom: 12px;
      }

      h3 {
        font-size: 18px;
        color: #2c3e50;
        margin: 0 0 8px;
      }

      p {
        color: #606266;
        margin: 0;
      }
    }
  }

  .instructions-content {
    padding: 20px 0;

    h3 {
      font-size: 18px;
      color: #2c3e50;
      margin: 0 0 16px;
    }

    ul {
      list-style: none;
      padding: 0;
      margin: 0 0 24px;

      li {
        position: relative;
        padding-left: 20px;
        margin-bottom: 12px;
        color: #606266;

        &:before {
          content: '';
          position: absolute;
          left: 0;
          top: 8px;
          width: 6px;
          height: 6px;
          border-radius: 50%;
          background: #409EFF;
        }
      }
    }
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
